//
//  AppDelegate.m
//  GameSky
//
//  Created by lanou on 16/1/9.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "AppDelegate.h"
#import "GSNetStaus.h"

#import "GSNewFeatureViewController.h"

#import <AFNetworking.h>


#import "ChooseControllerTool.h"

@interface AppDelegate ()<UIAlertViewDelegate>

@property (nonatomic, strong) FMDatabase *db;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    // 1.展示版本新特性;
    [ChooseControllerTool chooseRootController];
    
    // 2.监控当前网络环境;
    AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
    [manger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [GSNetStaus sharedHandle].reachable = @"WiFi";
                NSLog(@"WIFI网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [GSNetStaus sharedHandle].reachable = @"WWAN";
                NSLog(@"移动网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:{
                [GSNetStaus sharedHandle].reachable = @"NotReachable";
                
                NSLog(@"没有网络");
            }
                break;
            case AFNetworkReachabilityStatusUnknown:
                [GSNetStaus sharedHandle].reachable = @"Unknown";
                NSLog(@"未知网络");
                break;
            default:
                break;
        }
    }];
    [manger startMonitoring];
    
    // 3.友盟社会化分享配置;
    // 添加友盟分享AppKey;
    [UMSocialData setAppKey:@"568a3499e0f55a3a3f000047"];
    // 设置分享到微信的AppId和分享URL链接;
    [UMSocialWechatHandler setWXAppId:@"wxd930ea5d5a258f4f" appSecret:@"568a3499e0f55a3a3f000047" url:@"http://www.umeng.com/social"];
    // 设置分享到QQ/Qzone的AppId和分享URL链接;
    [UMSocialQQHandler setQQWithAppId:@"100424468" appKey:@"568a3499e0f55a3a3f000047" url:@"http://www.umeng.com/social"];
    
    // 4.数据缓存;
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    // 创建文件夹(如果存在则不创建);
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager createDirectoryAtPath:[path stringByAppendingPathComponent:@"data"] withIntermediateDirectories:NO attributes:nil error:nil];
    // 拼接路径;
    NSString *pathString = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
    _db = [FMDatabase databaseWithPath:pathString];
    
    if (![_db open]) {
        NSLog(@"数据打开失败");
    }
    
    // 创建表格,保存已经订阅的专题
    if (![_db executeUpdate:@"create table IF NOT EXISTS SubscribeList(nodeIds text not NULL, cnt integer not NULL, sourceName text not NULL, imageData blob not NULL)"]) {
        NSLog(@"建表失败");
    }
    
    // 创建表格,保存搜索历史
    if (![_db executeUpdate:@"create table IF NOT EXISTS SearchHistoryList(history text not NULL)"]) {
        NSLog(@"创建搜索历史表格失败");
    }
    
    // 5.监听白天/夜间模式切换通知;
    [kNotificationCenter addObserver:self selector:@selector(nightFalling) name:DKNightVersionNightFallingNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(dawnComing) name:DKNightVersionDawnComingNotification object:nil];
    
    return YES;
}
// 通知方法;
- (void)nightFalling
{
    [DKNightVersionManager nightFalling];
}
- (void)dawnComing
{
    [DKNightVersionManager dawnComing];
}
// 移除通知;
- (void)dealloc
{
    [kNotificationCenter removeObserver:self];
}


- (void)skipBtnClick:(UIButton *)button
{
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {

    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou3g.www.GameSky" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"GameSky" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"GameSky.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
